#pragma once
#include <QString>
#include <stdint.h>
#include <unordered_map>
#include <future>
#include <mutex>

class Cpu;
class JsScriptManager
{
public:
    using JsScriptType = void(*)(QVariantMap);
private:
    JsScriptManager();
public:
    ~JsScriptManager();
public:
    static void init(Cpu *cpu);
    static std::future<QVariant> runOnAddon(const QString &script);
    static std::future<QVariant> runFunctionOnAddon(const QString &name, const QVariantList &args);
    static std::future<QVariant> runOnTab(const QString &tab, const QString &script);
    static std::future<QVariant> runFunctionOnTab(const QString &tab, const QString &name, const QVariantList &args);
private:
    std::future<QVariant> _runOnAddon(const QString &script);
    std::future<QVariant> _runFunctionOnAddon(const QString &name, const QVariantList &args);
    std::future<QVariant> _runOnTab(const QString &tab, const QString &script);
    std::future<QVariant> _runFunctionOnTab(const QString &tab, const QString &name, const QVariantList &args);
    uint64_t _add(uint64_t i);
    void _remove(uint64_t i);
private:
    void onJsScriptFinished(QVariantMap args);
private:
    std::mutex locker;
    uint64_t lastId = 0;
    std::unordered_map<uint64_t, std::promise<QVariant>> scripts = std::unordered_map<uint64_t, std::promise<QVariant>>(1024);
private:
    static JsScriptManager *_instance;
};

